<?php

Raise::load('core.RaiseValidator');
Raise::load('core.RaiseRegex');

/**
 * RaiseRegexValidator class
 * validates value using Perl-Compatible Regular Expressions (PCRE)
 *
 * @author Sam-Mauris Yong <hellclanner at live dot com>
 * @license http://www.opensource.org/licenses/bsd-license New BSD License
 * @package Raise.Core.Validator
 * @since 1.2
 */
class RaiseRegexValidator extends RaiseValidator {

    /**
     * The regular expression to check against
     * @var RaiseRegex
     */
    private $regex;

    /**
     * Create a new RaiseRegexValidator
     * @param RaiseRegex $regex The regular expression to use.
     */
    function __construct($regex){
        $this->regex($regex);
    }

    /**
     * Get or set the regular expression to use when validating
     * @param RaiseRegex $r (optional) If set, the new regular expression will be set.
     * @return RaiseRegex
     */
    public function regex($r = false){
        if(func_num_args() == 1){
            if(!($r instanceof RaiseRegex)){
                throw new RaiseInvalidArgumentException('RaiseRegexValidator::regex() expecting RaiseRegex as first parameter; ' . RaiseVariable::typeInfo($r) . ' was given instead.');
            }
            $this->regex = $r;
        }
        return $this->regex;
    }

    public function validate($value) {
        parent::validate($value);
        $result = $this->regex->match($value);
        if($result->count() > 0){
            return true;
        }
        return false;
    }

}
